package com.md.model.bo;

import lombok.Data;
import org.springframework.lang.NonNull;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author 刘骄阳
 * 2023-10-09 16:43
 */
@Data
public class CustomThreadFactory implements ThreadFactory {

  private String namePrefix;
  private ThreadGroup group;
  private AtomicLong count;

  public static CustomThreadFactory of(final String namePrefix) {
    CustomThreadFactory customThreadFactory = new CustomThreadFactory();
    customThreadFactory.setNamePrefix(namePrefix);
    customThreadFactory.setGroup(Thread.currentThread().getThreadGroup());
    customThreadFactory.setCount(new AtomicLong(1));
    return customThreadFactory;
  }


  /**
   * Constructs a new {@code Thread}.  Implementations may also initialize
   * priority, name, daemon status, {@code ThreadGroup}, etc.
   *
   * @param runnable a runnable to be executed by new thread instance
   * @return constructed thread, or {@code null} if the request to
   * create a thread is rejected
   */
  @Override
  public Thread newThread(@NonNull final Runnable runnable) {
    Thread thread = new Thread(this.group, runnable, this.namePrefix + "-" + this.count.incrementAndGet());
    // 如果是守护线程,则设置为非守护线程
    if (thread.isDaemon()) {
      thread.setDaemon(false);
    }
    // 判断优先级
    if (thread.getPriority() != Thread.NORM_PRIORITY) {
      thread.setPriority(Thread.NORM_PRIORITY);
    }
    return thread;
  }
}
